﻿using Microsoft.AspNetCore.Mvc;
using QingZhouLinYe.HttpApi.Models;
using SqlSugar;
using System.Diagnostics;

namespace QingZhouLinYe.HttpApi.Controllers
{
    [ApiController]
    [Route("[controller]/[Action]")]
    public class FangHuoDanWeiController : ControllerBase
    {
        private readonly SqlSugarClient _db;

        public FangHuoDanWeiController(SqlSugarClient db)
        {
            _db = db;
        }

        [HttpGet]
        public async Task<List<FangHuoDanWei>> Get()
        {
            return await _db.Queryable<FangHuoDanWei>()
                .ToListAsync();
        }

        [HttpGet]
        public async Task<List<FangHuoDanWei>> GetToTree(string code)
        {
            return await _db.Queryable<FangHuoDanWei>()
                .ToTreeAsync(fhdw => fhdw.Child,fhdw => fhdw.UpCode,code);
        }

        [HttpGet()]
        public async Task<FangHuoDanWei> getById(int fhdwid)
        {
            return await _db.Queryable<FangHuoDanWei>()
                .Where(fhdw => fhdw.Id == fhdwid)
                .SingleAsync();
        }

        [HttpPost]
        public async Task<int> Save(FangHuoDanWei fhdw)
        {
            try
            {
                _db.BeginTran();
                long x = await _db.Insertable(fhdw).ExecuteReturnBigIdentityAsync();  //返回最后插入数据的Id
                if(x != 0)
                {
                    _db.CommitTran();
                    return (int)x;
                }
            }catch(Exception ex)
            {
                _db.RollbackTran();
                Debug.WriteLine("发生错误：" + ex);
                return 0;
            }
            return 0;
        }

        [HttpPost]
        public async Task<int> Saves(List<FangHuoDanWei> fhdws)
        {
            try
            {
                _db.BeginTran();//开启事务
                await _db.Fastest<FangHuoDanWei>().BulkCopyAsync(fhdws);
                _db.CommitTran();//提交事务
            }
            catch (Exception ex)
            {
                _db.RollbackTran();  //事务回滚
                Debug.WriteLine("发生错误："+ex);
                return 0;
            }
            return 1;
        }
    }
}
